<template>
  <a-popover ref="popoverRef" :open="visible" trigger="click" :destroyTooltipOnHide="true">
    <template #title>
      <div class="flex flex-row">
        <div class="flex-shrink-0">标题</div>
        <div
          class="flex-1 w-0 text-center cursor-move"
          ref="moveHotContainerRef"
          @mousedown="onMouseDown"
        >
          中间部分
        </div>
        <div class="flex-shrink-0" @click="hide">关闭</div>
      </div>
    </template>
    <template #content>
      <div>
        <p>Content</p>
        <p>Content</p>
      </div>
    </template>
    <a-button type="primary" @click="onShow" size="small">点我</a-button>
  </a-popover>
</template>

<script setup lang="ts">
import { ref } from 'vue'
const popoverRef = ref<any>()
const moveHotContainerRef = ref<HTMLDivElement>()
const visible = ref(false)
function hide() {
  visible.value = false
}
function onShow() {
  visible.value = true
}

function onMouseDown(e: MouseEvent) {
  // 获取当前点击位置的x，y坐标
  const { clientX, clientY } = e
  const target = popoverRef.value.getPopupDomNode() as HTMLElement

  let styleLeft: number
  let styleTop: number
  // 获取可被拖动元素左顶点的x,y坐标
  const style = getDomCurrentStyle(target as HTMLElement)
  if (style.left.indexOf('%') >= 0) {
    styleLeft = +document.body.clientWidth * (+style.left.replace(/\%/g, '') / 100)
    styleTop = +document.body.clientHeight * (+style.top.replace(/\%/g, '') / 100)
  } else {
    styleLeft = +style.left.replace(/\px/g, '')
    styleTop = +style.top.replace(/\px/g, '')
  }

  function onMouseMove(evt: MouseEvent) {
    // 获取当前拖动到的点的x，y坐标，并计算x，y轴的偏移量
    const dx = evt.clientX - clientX
    const dy = evt.clientY - clientY
    // 可被拖动元素初始左顶点的x,y坐标加上偏移量，得到最新左顶点的x,y坐标
    target.style.left = `${styleLeft + dx}px`
    target.style.top = `${styleTop + dy}px`
    console.log('document.onmousemove', target, styleLeft + dx)
    return false
  }
  document.addEventListener('mousemove', onMouseMove)

  function onMouseUp() {
    document.removeEventListener('mousemove', onMouseMove)
    document.removeEventListener('mouseup', onMouseUp)
  }
  document.addEventListener('mouseup', onMouseUp)
}
function getDomCurrentStyle(dom: HTMLElement): CSSStyleDeclaration {
  // @ts-ignore
  return (dom.currentStyle as CSSStyleDeclaration) || window.getComputedStyle(dom, null)
}
</script>

<style scoped></style>
